package com.common.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import org.apache.commons.codec.binary.Base64;

public class AesEncryptUtils {

    private static final String SECRET = "AES";

    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";

    private static final String key = "QHmiZcntUCI0y2rb";

    static{
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * AES加密ECB模式PKCS7Padding填充方式
     * @param str 字符串
     * @return 加密字符串
     * @throws Exception 异常信息
     */
    public static String encrypt(String str) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
        byte[] doFinal = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
        return new String(Base64.encodeBase64(doFinal));
    }

    /**
     * AES解密ECB模式PKCS7Padding填充方式
     * @param str 字符串
     * @return 解密字符串
     * @throws Exception 异常信息
     */
    public static String decrypt(String str) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
        byte[] doFinal = cipher.doFinal(Base64.decodeBase64(str));
        return new String(doFinal);
    }

    /**
     * AES加密ECB模式PKCS7Padding填充方式
     * @param str 字符串
     * @return 加密后byte数组
     * @throws Exception 异常信息
     */
    public static byte[] encryptByte(String str) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
        byte[] doFinal = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
        return doFinal;
    }

    /**
     * AES解密ECB模式PKCS7Padding填充方式
     * @param byte数组
     * @return 解密字符串
     * @throws Exception 异常信息
     */
    public static String decryptByte(byte[] str) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
        byte[] doFinal = cipher.doFinal(str);
        return new String(doFinal);
    }

    public static void main(String[] args) throws Exception {
        String str = "a1234567";
        System.out.println("字符串：" + str);
        byte[] encryptStr = encryptByte(str);
        System.out.println("加密后字符串：" + encryptStr);
        String decryptStr = decryptByte(encryptStr);
        System.out.println("解密后字符串：" + decryptStr);
    }


}
